package com.zhiyin.seal.controller;

import com.google.common.collect.Lists;
import com.zhiyin.seal.entity.bo.*;
import com.zhiyin.seal.entity.dto.AddApprovalProcessDTO;
import com.zhiyin.seal.entity.dto.ApprovalProcessDTO;
import com.zhiyin.seal.entity.dto.ApprovalUserDTO;
import com.zhiyin.seal.entity.dto.ResponseDTO;
import com.zhiyin.seal.entity.vo.*;
import com.zhiyin.seal.service.ApprovalService;
import com.zhiyin.seal.service.CompanyService;
import com.zhiyin.seal.service.SealService;
import com.zhiyin.seal.service.UserService;
import com.zhiyin.seal.util.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 审批业务控制器
 */
@RestController
@RequestMapping("/approvalprocess")
public class ApprovalController {

    @Autowired
    ApprovalService approvalService;

    @Autowired
    UserService userService;

    @Autowired
    SealService sealService;

    @Autowired
    CompanyService companyService;

    @GetMapping("/list")
    public ResponseDTO<List<ApprovalProcessVo>> getApprovalProcessList(@RequestParam Long companyId){
        return ResponseDTO.succData(BeanUtil.copyList(approvalService.getApprovalProcessList(companyId),ApprovalProcessVo.class));
    }

    @GetMapping("/listbyseal")
    public ResponseDTO<List<ApprovalProcessVo>> getApprovalProcessListBySealId(@RequestParam Long sealId){
        return ResponseDTO.succData(BeanUtil.copyList(approvalService.getApprovalProcessListBySealId(sealId),ApprovalProcessVo.class));
    }

    @PostMapping("/update")
    public ResponseDTO<Boolean> updateApprovalProcess(@RequestBody ApprovalProcessDTO approvalProcessDTO){
        return ResponseDTO.succData(approvalService.updateApprovalProcess(BeanUtil.copy(approvalProcessDTO, ApprovalProcessBo.class)));
    }

    @GetMapping("/delete")
    public ResponseDTO<Boolean> removeApprovalProcess(@RequestParam Long processId){
        return ResponseDTO.succData(approvalService.removeApprovalProcess(processId));
    }

    @GetMapping("/detail")
    public ResponseDTO<ApprovalProcessDetailVo> getApprovalProcessDetail(@RequestParam Long processId){
        // 查询审批流信息
        ApprovalProcessBo approvalProcessBo = approvalService.getApprovalProcessById(processId);
        if(approvalProcessBo == null){
            return ResponseDTO.succData(null);
        }
        Long companyId=approvalProcessBo.getCompanyId();
        List<ApprovalUserBo> approvalUserBoList = approvalService.getApprovalUserList(processId);
        List<ApprovalCCBo> approvalCCBoList = approvalService.getApprovalCCList(processId);

        // 声明审批流视图对象
        ApprovalProcessDetailVo detailVo = new ApprovalProcessDetailVo();
        // 赋值审批流信息
        detailVo.setApprovalProcess(BeanUtil.copy(approvalProcessBo,ApprovalProcessVo.class));
        ApprovalProcessVo approvalProcessVo = detailVo.getApprovalProcess();
        Long departmentId = approvalProcessVo.getDepartmentId();
        if(departmentId == 0){
            approvalProcessVo.setDepartmentName("公司全员");
        } else {
            CompanyDepartmentBo companyDepartmentBo = companyService.getDepartmentById(departmentId);
            if(companyDepartmentBo != null){
                approvalProcessVo.setDepartmentName(companyDepartmentBo.getName());
            }
        }
        Long sealId = approvalProcessVo.getSealId();
        SealBo sealBo = sealService.getSealByIdAndCompany(sealId,approvalProcessVo.getCompanyId());
        if(sealBo != null){
            approvalProcessVo.setSealName(sealBo.getName());
        }
        // 赋值审批人
        List<ApprovalUserVo> approvalUserVoList = Lists.newArrayList();
        ApprovalUserVo approvalUserVo = new ApprovalUserVo();
        approvalUserVo.setLevel(0);
        approvalUserVo.setIds(Lists.newArrayList());
        approvalUserVoList.add(approvalUserVo);
        int level = 0;
        for (ApprovalUserBo approvalUserBo : approvalUserBoList) {
            if(approvalUserBo.getLevel() == level){
                approvalUserVo = approvalUserVoList.get(level);
                List<Long> userIds = approvalUserVo.getIds();
                userIds.add(approvalUserBo.getUserId());
            } else {
                approvalUserVo = new ApprovalUserVo();
                approvalUserVo.setLevel(approvalUserBo.getLevel());
                List<Long> userIds = Lists.newArrayList();
                userIds.add(approvalUserBo.getUserId());
                approvalUserVo.setIds(userIds);
                approvalUserVoList.add(approvalUserVo);
            }
            level = approvalUserBo.getLevel();
        }
        // 拼接用户名称
        for (ApprovalUserVo userVo : approvalUserVoList) {
            if(userVo.getIds().size() > 0){
                List<UserBo> userBoList = userService.getUserListByUserIdsAndCompany(userVo.getIds(),companyId);
                List<String> userNames = Lists.newArrayList();
                for (UserBo userBo : userBoList) {
                    userNames.add((userBo.getNickName()));
                }
                userVo.setNames(StringUtils.join(userNames,","));
                userVo.setUserVoList(BeanUtil.copyList(userBoList, UserVo.class));
            } else {
                userVo.setNames("无");
                continue;
            }
        }
        detailVo.setApprovalUserList(approvalUserVoList);

        // 赋值抄送人
        ApprovalCCUserVo approvalCCUserVo = new ApprovalCCUserVo();
        List<Long> ccUserIds = Lists.newArrayList();
        approvalCCUserVo.setIds(ccUserIds);
        approvalCCUserVo.setNames("无");
        if(approvalCCBoList.size() > 0){
            for (ApprovalCCBo approvalCCBo : approvalCCBoList) {
                ccUserIds.add(approvalCCBo.getUserId());
            }
            List<UserBo> userBoList = userService.getUserListByUserIdsAndCompany(ccUserIds,companyId);
            List<String> userNames = Lists.newArrayList();
            for (UserBo userBo : userBoList) {
                userNames.add((userBo.getNickName()));
            }
            approvalCCUserVo.setNames(StringUtils.join(userNames,","));
            approvalCCUserVo.setUserVoList(BeanUtil.copyList(userBoList, UserVo.class));
        }

        detailVo.setCcUser(approvalCCUserVo);

        return ResponseDTO.succData(detailVo);
    }

    @PostMapping("/add")
    public ResponseDTO<Boolean> addApprovalProcess(@RequestBody AddApprovalProcessDTO approvalProcessDTO){
        ApprovalProcessBo approvalProcessBo = BeanUtil.copy(approvalProcessDTO.getApprovalProcess(),ApprovalProcessBo.class);
        Long processId = approvalProcessBo.getId();
        // 判断审批流id，如果为0则插入，否则更新
        if(processId == 0){
            // 查询是否存已经设置过审批流
            Boolean result = approvalService.getHasApprovalProcess(approvalProcessBo.getSealId(),
                    approvalProcessBo.getDepartmentId(),
                    approvalProcessBo.getCompanyId());
            if(result){
                return ResponseDTO.succData(false);
            }
            processId = approvalService.addApprovalProcess(approvalProcessBo);
        } else {
            // 查询当前公司选择的部门，印章的审批流id
            List<Long> deparmentIds = Lists.newArrayList();
            deparmentIds.add(approvalProcessDTO.getApprovalProcess().getDepartmentId());
            Long pId = approvalService.getApprovalProcessId(approvalProcessDTO.getApprovalProcess().getSealId(),deparmentIds,approvalProcessDTO.getApprovalProcess().getCompanyId());
            if(pId == null || pId.equals(processId)){
                approvalService.updateApprovalProcess(approvalProcessBo);
            } else {
                return ResponseDTO.succData(false);
            }
        }
        if(processId !=0){
            // 清空审批人
            approvalService.removeApprovalUserList(processId);
            List<ApprovalUserBo> approvalUserBoList = Lists.newArrayList();

            List<ApprovalUserDTO> approvalUserDT0List = approvalProcessDTO.getApprovalUserList();
            for (ApprovalUserDTO approvalUserDTO : approvalUserDT0List) {
                Integer level = approvalUserDTO.getLevel();
                List<Long> userIds = approvalUserDTO.getIds();
                for (Long userId : userIds) {
                    ApprovalUserBo approvalUserBo = new ApprovalUserBo();
                    approvalUserBo.setLevel(level);
                    approvalUserBo.setUserId(userId);
                    approvalUserBoList.add(approvalUserBo);
                }
            }
            // 重新插入审批人
            if(approvalUserBoList.size() > 0){
                approvalService.addApprovalUserList(processId,approvalUserBoList);
            }
            // 清空抄送人
            approvalService.removeApprovalCCList(processId);
            List<Long> ccUserIds = approvalProcessDTO.getCcUserList();
            if(ccUserIds.size() > 0){
                List<ApprovalCCBo> approvalCCBoList = Lists.newArrayList();
                for (Long ccUserId : ccUserIds) {
                    ApprovalCCBo approvalCCBo = new ApprovalCCBo();
                    approvalCCBo.setUserId(ccUserId);
                    approvalCCBoList.add(approvalCCBo);
                }
                // 重新插入抄送人
                approvalService.addApprovalCCList(processId,approvalCCBoList);
            }
        }

        return ResponseDTO.succData(true);
    }

    @PostMapping("/set")
    public ResponseDTO<Boolean> setApprovalProcess(@RequestBody AddApprovalProcessDTO approvalProcessDTO){
        ApprovalProcessBo approvalProcessBo = BeanUtil.copy(approvalProcessDTO.getApprovalProcess(),ApprovalProcessBo.class);
        Long processId = approvalProcessBo.getId();
        // 判断审批流id，如果为0则插入，否则更新
        if(processId == 0){
            // 查询是否存已经设置过审批流
            ApprovalProcessBo apBo = approvalService.getApprovalProcessByNameSealIdCompanyId(approvalProcessBo.getName(),
                    approvalProcessBo.getSealId(),
                    approvalProcessBo.getCompanyId());
            if(apBo!= null){
                return ResponseDTO.succData(false);
            }
            processId = approvalService.addApprovalProcess(approvalProcessBo);
        } else {
            // 更新审批流
            approvalService.updateApprovalProcess(approvalProcessBo);
        }
        if(processId !=0){
            // 清空审批人
            approvalService.removeApprovalUserList(processId);
            List<ApprovalUserBo> approvalUserBoList = Lists.newArrayList();
            List<ApprovalUserDTO> approvalUserDT0List = approvalProcessDTO.getApprovalUserList();
            for (ApprovalUserDTO approvalUserDTO : approvalUserDT0List) {
                Integer level = approvalUserDTO.getLevel();
                List<Long> userIds = approvalUserDTO.getIds();
                for (Long userId : userIds) {
                    ApprovalUserBo approvalUserBo = new ApprovalUserBo();
                    approvalUserBo.setLevel(level);
                    approvalUserBo.setUserId(userId);
                    approvalUserBoList.add(approvalUserBo);
                }
            }
            // 重新插入审批人
            if(approvalUserBoList.size() > 0){
                approvalService.addApprovalUserList(processId,approvalUserBoList);
            }
            // 清空抄送人
            approvalService.removeApprovalCCList(processId);
            List<Long> ccUserIds = approvalProcessDTO.getCcUserList();
            if(ccUserIds.size() > 0){
                List<ApprovalCCBo> approvalCCBoList = Lists.newArrayList();
                for (Long ccUserId : ccUserIds) {
                    ApprovalCCBo approvalCCBo = new ApprovalCCBo();
                    approvalCCBo.setUserId(ccUserId);
                    approvalCCBoList.add(approvalCCBo);
                }
                // 重新插入抄送人
                approvalService.addApprovalCCList(processId,approvalCCBoList);
            }
        }

        return ResponseDTO.succData(true);
    }

    @GetMapping("/apply")
    public ResponseDTO<ApprovalProcessDetailVo> getApplyApprovalProcessDetail(@RequestParam Long sealId,@RequestParam Long userId,@RequestParam Long companyId){
        // 查询用户所在部门
        Long departmentId = companyService.getUserDepartmentId(companyId,userId);
        // 查询当前部门所有的父节点id
        List<Long> deparmentIds = companyService.getParentDepartmentIds(departmentId);
        deparmentIds.add(0l);
        // 查询匹配的审批流
        Long processId = approvalService.getApprovalProcessId(sealId,deparmentIds,companyId);

        return getApprovalProcessDetail(processId);
    }
}